package svrConnectMgr

import (
	"encoding/base64"
	"encoding/json"

	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
)

type wsClient struct {
	conn           *websocket.Conn
	chan_to_client chan ([]byte)
}

func (c wsClient) read() {
	for {
		mt, message, err := c.conn.ReadMessage()
		if err != nil {
			logrus.Errorln("read:", err)
			break
		}
		logrus.Debugln("recv: %s", message)
		//读取成功，解包处理
		go c.handleRequest(mt, message)
	}
}

func (c wsClient) write(data []byte) {
	c.chan_to_client <- data
}

func (c wsClient) start_push() {
	for {
		err := c.conn.WriteMessage(1, <-c.chan_to_client)
		if err != nil {
			logrus.Error("write to ws ", c.conn.RemoteAddr().String(), " failed! err:", err.Error())
			return
		}
	}
}

func (c wsClient) handleRequest(mt int, req_buffer []byte) {
	var transPack ProtoTransPack
	err := json.Unmarshal(req_buffer, &transPack)
	if err != nil {
		logrus.Errorln("parse req failed! ", err)
		return
	}
	if HandleCallback == nil {
		logrus.Errorln("no find callback!")
		return
	}
	req_json_str, err := base64.StdEncoding.DecodeString(transPack.Package)
	if err != nil {
		logrus.Errorln("parse package failed!")
		return
	}
	res_proto_name, res_package := HandleCallback(transPack.ProtoName, []byte(req_json_str))
	transPack.ProtoName = res_proto_name
	transPack.Package = base64.StdEncoding.EncodeToString(res_package)
	transPack.Rescode = 200

	res_buffer, _ := json.Marshal(transPack)
	err = c.conn.WriteMessage(mt, res_buffer) //回包给客户端
	if err != nil {
		logrus.Error("write to ws ", c.conn.RemoteAddr().String(), " failed! err:", err.Error())
		return
	}

}
